package com.fast.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

	/**
	 * cookie保存时间为1天
	 * 
	 * @param response
	 * @param key
	 * @param value
	 */
	public static void addCookie(HttpServletResponse response, String key, String value) {
		addCookie(response, key, value, "/");
	}

	/**
	 * 按照天数保存cookie
	 * 
	 * @param response
	 * @param key
	 * @param value
	 * @param day天数
	 */
	public static void addCookie(HttpServletResponse response, String key, String value, int day) {

		if (day <= 0) {
			day = 1;
		}
		int maxAge = day * 24 * 60 * 60;
		addCookie(response, key, value, "/", maxAge);
	}

	public static void addCookie(HttpServletResponse response, String key, String value, String path) {
		int maxAge = 24 * 60 * 60;
		addCookie(response, key, value, path, maxAge);
	}

	public static void addCookie(HttpServletResponse response, String key, String value, String path, int maxAge) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}

	/**
	 * 添加只读cookie
	 * 
	 * @param response
	 * @param key
	 * @param value
	 * @param path
	 * @param maxAge
	 */
	public static void addCookieReadOnly(HttpServletResponse response, String key, String value, String path,
			int maxAge) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(path);
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}

	/**
	 * 根据key值获取cookie
	 * 
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getCookie(HttpServletRequest request, String key) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			int len = cookies.length;
			for (int index = 0; index < len; index++) {
				if (cookies[index] != null && cookies[index].getName().equals(key)) {
					return cookies[index].getValue();
				}
			}
		}
		return null;
	}
}
